import React, { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Typography,
  Grid,
  Card,
  CardContent,
  CardMedia,
  CircularProgress,
  Alert,
  Paper,
  Pagination,
  Chip,
} from '@mui/material';
import { motion } from 'framer-motion';
import { DownloadRecordService, DownloadRecord } from '../services/DownloadRecordService';
import { ResourceService, Resource } from '../services/ResourceService';
import { useNavigate } from 'react-router-dom';
import { format } from 'date-fns';

// 格式化文件大小的辅助函数
const formatSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return parseFloat((bytes / Math.pow(1024, i)).toFixed(2)) + ' ' + sizes[i];
};

const PurchaseHistory: React.FC = () => {
  const [downloadRecords, setDownloadRecords] = useState<DownloadRecord[]>([]);
  const [resourceDetails, setResourceDetails] = useState<Record<number, Resource>>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [pageSize] = useState(10);
  const navigate = useNavigate();

  // 获取用户下载记录和资源详情
  useEffect(() => {
    const fetchDownloadRecords = async () => {
      try {
        setLoading(true);
        setError(null);
        const response = await DownloadRecordService.getDownloadRecordList(page, pageSize);
        const records = response.records || [];
        setDownloadRecords(records);
        setTotalPages(Math.ceil(response.total / pageSize));
        
        // 获取每条下载记录对应的资源详情
        const resourceDetailsMap: Record<number, Resource> = {};
        
        // 使用 Promise.all 并行获取所有资源详情
        await Promise.all(
          records.map(async (record) => {
            try {
              const resourceDetail = await ResourceService.getResourceById(record.resourceId.toString());
              resourceDetailsMap[record.resourceId] = resourceDetail;
            } catch (error) {
              console.error(`获取资源 ${record.resourceId} 详情失败:`, error);
            }
          })
        );
        
        setResourceDetails(resourceDetailsMap);
      } catch (err) {
        console.error('获取下载记录失败:', err);
        setError(err instanceof Error ? err.message : '获取下载记录失败');
      } finally {
        setLoading(false);
      }
    };

    fetchDownloadRecords();
  }, [page, pageSize]);

  const handleResourceClick = (resourceId: number) => {
    // 跳转到资源详情页
    navigate(`/resources/${resourceId}`);
  };

  const handlePageChange = (event: React.ChangeEvent<unknown>, value: number) => {
    setPage(value);
  };

  return (
    <Container maxWidth="lg">
      <Box
        component={motion.div}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        sx={{ mt: 4 }}
      >
        <Paper elevation={3} sx={{ p: 3 }}>
          <Typography variant="h5" gutterBottom>
            我的购买
          </Typography>
          
          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
              <CircularProgress />
            </Box>
          ) : error ? (
            <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>
          ) : downloadRecords.length === 0 ? (
            <Alert severity="info" sx={{ mb: 2 }}>暂无下载记录</Alert>
          ) : (
            <>
              <Grid container spacing={3}>
                {downloadRecords.map((record) => {
                  // 获取对应的资源详情
                  const resourceDetail = resourceDetails[record.resourceId];
                  
                  return (
                    <Grid item xs={12} sm={6} md={4} key={record.id}>
                      <Card 
                        onClick={() => handleResourceClick(record.resourceId)}
                        sx={{ 
                          height: '100%', 
                          display: 'flex', 
                          flexDirection: 'column',
                          cursor: 'pointer',
                          transition: 'all 0.3s ease',
                          '&:hover': {
                            transform: 'translateY(-4px)',
                            boxShadow: 6,
                          },
                        }}>
                        <CardMedia
                          component="img"
                          height="200"
                          image={resourceDetail?.coverUrl || resourceDetail?.coverImageUrl || '/covers/movie_cover_2.jpg'}
                          alt={resourceDetail?.title || `资源 ${record.resourceId}`}
                        />
                        <CardContent sx={{ flexGrow: 1 }}>
                          <Typography gutterBottom variant="h6" component="div">
                            {resourceDetail?.title || `资源 ${record.resourceId}`}
                          </Typography>
                          {resourceDetail && (
                            <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }} noWrap>
                              {resourceDetail.description}
                            </Typography>
                          )}
                          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mt: 1 }}>
                            <Chip 
                              label={`消耗积分: ${record.pointsUsed}`} 
                              color="primary" 
                              size="small" 
                              sx={{ mr: 1 }}
                            />
                            <Typography variant="body2" color="text.secondary">
                              {format(new Date(record.downloadTime), 'yyyy-MM-dd HH:mm')}
                            </Typography>
                          </Box>
                        </CardContent>
                      </Card>
                    </Grid>
                  );
                })}
              </Grid>
              
              {/* 分页控件 */}
              {totalPages > 1 && (
                <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
                  <Pagination 
                    count={totalPages} 
                    page={page} 
                    onChange={handlePageChange} 
                    color="primary" 
                  />
                </Box>
              )}
            </>
          )}
        </Paper>
      </Box>
    </Container>
  );
};

export default PurchaseHistory;